import React, { useState, useRef, useEffect } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import { Button, message, Popconfirm } from 'antd';

import ProForm, { ModalForm, ProFormText,ProFormSelect,ProFormTimePicker } from '@ant-design/pro-form';

import $api from '@/api';
import { RightSquareTwoTone } from '@ant-design/icons';

function Station() {
    const [showAddBox, setShowAddBox] = useState(false); // 添加弹窗是否显示
    const [editBox, setEditBox] = useState(false); // 编辑弹窗的提示
    const [editId, setEditId] = useState(null); // 当前的修改id

    const [sts, setSts] = useState({});//起点站点
    const [ets, setEts] = useState({});//到达站点

    const [scity, setScity] = useState('');//起点城市
    const [ecity, setEcity] = useState('');//到达城市

    const tableRef = useRef(); // 创建一个转发  关联protable组件实例
    const editFormRef = useRef(); // 创建一个编辑表单的转发
    const addFormRef = useRef(); // 创建一个新建表单的转发
    
    // 表格的列定义
    const columns = [
        {
            title: '线路编号',
            width: 80,
            dataIndex: 'flightNum',
            hideInSearch:true, //不显示在查询栏
        },
        {
            title: '起点城市',
            dataIndex: 'startCity',
        },
        {
            title: '到达城市',
            dataIndex: 'arriveCity',
        },
        {
            title: '票价',
            hideInSearch: true,
            render(_, record) {
                return record.ticketPrice/100
            }
        },
        ,
        {
            title: '售票数量',
            dataIndex: 'maxNum',
            hideInSearch:true,
        },
        {
            title: '预售天数',
            dataIndex: 'preDay',
            hideInSearch:true,
        },
        {
            title: '操作',
             hideInSearch:true,
            render(_,record) {
                return (
                    <>
                        <Button
                            onClick={ async () => {
                                setEditId(record._id); // 设置一个当前的修改 记录的id
                                
                                await getStations(record.startCity, 's');
                                await getStations(record.arriveCity, 'e');

                                // 设置弹出的编辑表单的 表单默认值
                                setTimeout(() => {
                                     editFormRef.current.setFieldsValue({ ...record, ticketPrice: record.ticketPrice / 100 });
                                });
                                setEditBox(true);
                            }}
                            >
                            修改
                        </Button>

                        <Popconfirm
                            title="确认删除该信息？"
                            okText="Yes"
                            cancelText="No"
                            onConfirm={
                                () => handleDelete(record._id)
                            }>
                            <Button>删除</Button>
                        </Popconfirm>
                    
                    </>
                )
            },
        }
        
    ];


    // 获取表格数据的函数
    const getTableData = async (params) => {

        const { pageSize, current, ...postData } = params;


        // params会把当前的protable中需要的参数都集合给我们
        let _res = await $api.post('/flight/admin/getAll', {
            limit: pageSize,
            page: current,
            ...postData,
        })
        // console.log(_res);
        const { success, data, count } = _res.data;
        if (success) {
            // 在getTableData当中一定要返回一个对象，这个对象就是表格需要渲染的数据
            return {
                success,  // success 是表格判断是否加载数据成功的依据
                data,  // data 就是表格的数据
                total:count,  // total 表格能实现分页的基础
            }
        }
    };

    // 删除数据
    const handleDelete = async (id) => {
        let _res = await $api.post('/flight/del',{id})
        const { success } = _res.data;
        if (!success) message.error('删除失败');
        if (success) {
            tableRef.current.reload();
             message.success('删除成功')
        };
    }

    useEffect(() => {
        if(scity) getStations(scity,'s')
    },[scity])

    useEffect(() => {
        if(ecity) getStations(ecity,'e')
    },[ecity])

    // 根据城市名称获取对应的站点
    const getStations = async (cityName,type) => {
        let res = await $api.post('/station/getAll', { cityName});
        const { data } = res.data;
        const _temobj = {};
        data.forEach(element => {
            _temobj[element.stationName]=element.stationName
        })
        // 设置起点站点可选择的内容
        if (type == 's') {
            setSts(_temobj)
        }
        if (type == 'e') {
            setEts(_temobj)
        }

    }

    return (
        <PageContainer>
            <ProTable rowKey='_id' actionRef={tableRef} columns={columns} request={getTableData} toolBarRender={() => [
                <Button key="primary" type="primary" onClick={()=>setShowAddBox(true)}>
                    新建
                </Button>,
            ]} />

            {/* 添加站点浮层表单 */}
            <ModalForm
                formRef={addFormRef}
                visible={showAddBox}
                onVisibleChange={setShowAddBox}
                // onFinish函数就会得到用户填写的表单内容，执行添加请求
                onFinish={ async (data) => {
                    let _res = await $api.post('/flight/add',
                        // 价格精确到分
                        { ...data, ticketPrice: data.ticketPrice * 100 }
                    )
                    const { success } = _res.data;
                    if (!success) message.error('添加失败');
                    if (success) {
                        tableRef.current.reload();
                        message.success('添加成功')
                    };
                    addFormRef.current.resetFields(); // 重置表单
                    return success
                }
                }
            >
                 <ProForm.Group>
                    <ProFormText
                        width="md"
                        name="flightNum"
                        label="线路编号"
                        tooltip="最长为10 位"
                        placeholder="请输入编号"
                    />
                    <ProFormText
                        width="md"
                        name="preDay"
                        label="预售天数"
                        placeholder="预售天数"
                    />
                </ProForm.Group>

                <ProForm.Group>
                    <ProFormTimePicker
                        width="md"
                        name="startTime"
                        label="发车时间"
                        placeholder="请输入出发时间"
                    />
                </ProForm.Group>


                <ProForm.Group>
                    <ProFormText
                        width="md"
                        name="startCity"
                        label="出发城市"
                        tooltip="最长为10 位"
                        placeholder="请输入出发城市"
                        onChange={ev=>setScity(ev.target.value)}
                    />
                    <ProFormText
                        width="md"
                        name="arriveCity"
                        label="到达城市"
                        placeholder="请输入到达城市"
                        onChange={ev => setEcity(ev.target.value)}
                    />
                </ProForm.Group>

                <ProForm.Group>
                    <ProFormText
                        width="md"
                        name="ticketPrice"
                        label="票价"
                        placeholder="请输入票价"
                    />
                    <ProFormText
                        width="md"
                        name="maxNum"
                        label="售票数量"
                        placeholder="情输入售票数量"
                    />
                </ProForm.Group>

                <ProForm.Group>
                    <ProFormSelect
                        fieldProps={{mode:'tags'}}
                        name="startStations"
                        label="出发站点"
                        valueEnum={sts}
                    />
                    <ProFormSelect
                        fieldProps={{mode:'tags'}}
                        name="arriveStations"
                        label="到达站点"
                        valueEnum={ets}
                    />
                </ProForm.Group>

                
            </ModalForm>

            {/* 修改操作 */}
         <ModalForm
            formRef={editFormRef}
            visible={editBox}
            onVisibleChange={setEditBox}
            onFinish={async (data) => {
            // onFinish 函数就会得到用户填写的表单的内容 执行添加请求
                let _res = await $api.post('/flight/edit',
                 // 价格精确到分
                    {
                        ...data,
                        id:editId,
                        ticketPrice: data.ticketPrice * 100
                    }
                );
            const { success } = _res.data;

            if (!success) message.error('编辑失败');
            if (success) {
                tableRef.current.reload();
                message.success('编辑成功');
            }
            editFormRef.current.resetFields(); // 重置表单
            return success;
            }}
        >
            <ProForm.Group>
                    <ProFormText
                        width="md"
                        name="flightNum"
                        label="线路编号"
                        tooltip="最长为10 位"
                        placeholder="请输入编号"
                    />
                    <ProFormText
                        width="md"
                        name="preDay"
                        label="预售天数"
                        placeholder="预售天数"
                    />
                </ProForm.Group>

                <ProForm.Group>
                    <ProFormTimePicker
                        width="md"
                        name="startTime"
                        label="发车时间"
                        placeholder="请输入出发时间"
                    />
                </ProForm.Group>

                <ProForm.Group>
                    <ProFormText
                        width="md"
                        name="startCity"
                        label="出发城市"
                        tooltip="最长为10 位"
                        placeholder="请输入出发城市"
                        onChange={ev=>setScity(ev.target.value)}
                    />
                    <ProFormText
                        width="md"
                        name="arriveCity"
                        label="到达城市"
                        placeholder="请输入到达城市"
                        onChange={ev => setEcity(ev.target.value)}
                    />
                </ProForm.Group>

                <ProForm.Group>
                    <ProFormText
                        width="md"
                        name="ticketPrice"
                        label="票价"
                        placeholder="请输入票价"
                    />
                    <ProFormText
                        width="md"
                        name="maxNum"
                        label="售票数量"
                        placeholder="情输入售票数量"
                    />
                </ProForm.Group>

                <ProForm.Group>
                    <ProFormSelect
                        fieldProps={{mode:'tags'}}
                        name="startStations"
                        label="出发站点"
                        valueEnum={sts}
                    />
                    <ProFormSelect
                        fieldProps={{mode:'tags'}}
                        name="arriveStations"
                        label="到达站点"
                        valueEnum={ets}
                    />
                </ProForm.Group>

        </ModalForm>

        </PageContainer>
    )
}

export default Station;